package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.TProd;
import com.ruoyi.system.domain.TProdTotal;
import com.ruoyi.system.domain.TProjectAim;
import com.ruoyi.system.domain.vo.PieVO;
import com.ruoyi.system.domain.vo.ProdMonthTotalVO;
import com.ruoyi.system.domain.vo.ProdPlanVO;
import com.ruoyi.system.domain.vo.ProdYearTotalVO;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class MainServiceImpl implements IMainService {
    @Autowired
    private ITProjectAimService projectAimService;
    @Autowired
    private ITProdTotalService prodTotalService;
    @Autowired
    private ITProdRecordService prodRecordService;
    @Autowired
    private ITProdTaskService prodTaskService;
    @Autowired
    private ITProdService prodService;
    @Autowired
    private ISysDictDataService dictDataService;

    public void countProjectYearProd(Long projectId) {
        Date now = new Date();
        //查询项目总生产目标
        TProdTotal total = prodTotalService.getOne(new LambdaQueryWrapper<TProdTotal>().eq(TProdTotal::getProjectId, projectId));
        if(Objects.isNull(total)){
            return;
        }
        //查询项目已生产产品数量
        int finishNum = prodRecordService.sumRecord(projectId);
        //计算据目标完成日期相距天数
        int totalDays = DateUtils.daysBetween(now, total.getFinishDate());
        if (totalDays > 0) {
            //年目标产量
            int aimNum = 0;
            //今年已生产的数量
            int yearFinishNum = prodRecordService.sumYearRecord(projectId);
            //判断完成日期是否是今年，是则剩余目标产量即为年目标
            if(total.getFinishDate().getYear() == now.getYear()){
                if (total.getProdNum() > finishNum) {
                    aimNum = total.getProdNum() - finishNum + yearFinishNum;
                }else {
                    aimNum = yearFinishNum;
                }
            }else if(total.getFinishDate().getYear() > now.getYear()) {
                //计算每天应生产数量
                int dayNum = 0;
                int days = 0;
                if (total.getProdNum() > finishNum) {
                    dayNum = (int) ((total.getProdNum() - finishNum) / totalDays);
                }
                //今年剩余多少天
                days = DateUtils.remainYearDays();
                aimNum = dayNum * days + yearFinishNum;
            }
            TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                    .eq(TProjectAim::getProjectId, projectId)
                    .eq(TProjectAim::getYear,LocalDate.now().getYear()));
            if (Objects.isNull(projectAim)) {
                projectAim = new TProjectAim();
                projectAim.setYear(LocalDate.now().getYear() + "");
                projectAim.setProjectId(projectId);
                projectAim.setYearNum(aimNum);
                projectAimService.save(projectAim);
            } else {
                projectAim.setYearNum(aimNum);
                projectAimService.updateById(projectAim);
            }
        }
    }

    @Override
    public void countProjectMonthProd(Long projectId) {
        Date now = new Date();
        //查询项目总生产目标
        TProdTotal total = prodTotalService.getOne(new LambdaQueryWrapper<TProdTotal>().eq(TProdTotal::getProjectId, projectId));
        if(Objects.isNull(total)){
            return;
        }
        //查询项目已生产产品数量
        int finishNum = prodRecordService.sumRecord(projectId);
        //计算据目标完成日期相距天数
        int totalDays = DateUtils.daysBetween(now, total.getFinishDate());
        if (totalDays > 0) {
            //月目标产量
            int aimNum = 0;
            //计算每天应生产数量
            int dayNum = 0;
            int days = 0;
            //本月应完成产量--还需加上本月已完成数量
            int monthFinishNum = prodRecordService.sumMonthRecord(projectId);
            //判断完成日期是否是本月，是则剩余目标产量即为月目标
            if(total.getFinishDate().getYear() == now.getYear() && total.getFinishDate().getMonth() == now.getMonth()){
                if (total.getProdNum() > finishNum) {
                    aimNum = total.getProdNum() - finishNum + monthFinishNum;
                }else {
                    aimNum = monthFinishNum;
                }
            }else if(total.getFinishDate().getTime() > now.getTime()){
                //完成日期大于本月，计算每天产量
                if (total.getProdNum() > finishNum) {
                    dayNum = (int) ((total.getProdNum() - finishNum) / totalDays);
                }
                days = DateUtils.remainMonthDays();
                aimNum = dayNum * days + monthFinishNum;
            }
            TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                    .eq(TProjectAim::getProjectId, projectId)
                    .eq(TProjectAim::getYear,LocalDate.now().getYear()));
            if (Objects.isNull(projectAim)) {
                projectAim = new TProjectAim();
                projectAim.setProjectId(projectId);
                projectAim.setMonthNum(aimNum);
                projectAim.setYear(LocalDate.now().getYear()+"");
                projectAimService.save(projectAim);
            } else {
                projectAim.setMonthNum(aimNum);
                projectAimService.updateById(projectAim);
            }
        }
    }

    @Override
    public void countProjectDayProd(Long projectId) {
        Date now = new Date();
        //查询项目总生产目标
        TProdTotal total = prodTotalService.getOne(new LambdaQueryWrapper<TProdTotal>().eq(TProdTotal::getProjectId, projectId));
        if(Objects.isNull(total)){
            return;
        }
        //查询项目已生产产品数量
        int finishNum = prodRecordService.sumRecord(projectId);
        //计算据目标完成日期相距天数
        int totalDays = DateUtils.daysBetween(now, total.getFinishDate());
        if (totalDays > 0) {
            //计算每天应生产数量 -- 还需加上当天已生产数量
            int dayFinishNum = prodRecordService.sumDayRecord(projectId);
            int dayNum = 0;
            //判断完成日期是否是本月，是则剩余目标产量即为月目标
            if(total.getFinishDate().getYear() == now.getYear() && total.getFinishDate().getMonth() == now.getMonth() && total.getFinishDate().getDay() == now.getDay()){
                if (total.getProdNum() > finishNum) {
                    dayNum = total.getProdNum() - finishNum + dayFinishNum;
                }else {
                    dayNum = dayFinishNum;
                }

            }else if(total.getFinishDate().getTime() > now.getTime()){
                if (total.getProdNum() > finishNum) {
                    dayNum = (int) ((total.getProdNum() - finishNum) / totalDays);
                    dayNum += dayFinishNum;
                }
            }
            TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                    .eq(TProjectAim::getProjectId, projectId)
                    .eq(TProjectAim::getYear,LocalDate.now().getYear()));
            if (Objects.isNull(projectAim)) {
                projectAim = new TProjectAim();
                projectAim.setProjectId(projectId);
                projectAim.setDayNum(dayNum);
                projectAim.setYear(LocalDate.now().getYear()+"");
                projectAimService.save(projectAim);
            } else {
                projectAim.setDayNum(dayNum);
                projectAimService.updateById(projectAim);
            }
        }
    }

    @Override
    public ProdPlanVO finishSchedule(Long projectId) {
        ProdPlanVO prodPlan = new ProdPlanVO();
        //查询项目总生产目标
        TProdTotal total = prodTotalService.getOne(new LambdaQueryWrapper<TProdTotal>().eq(TProdTotal::getProjectId, projectId));
        if(Objects.isNull(total)){
            return prodPlan;
        }
        int totalDays = DateUtils.daysBetween(new Date(), total.getFinishDate());
        int year = totalDays/365;
        int month = totalDays%365/30;
        int day = totalDays%365%30;
        prodPlan.setTimer(year + "年" + month + "月" + day + "日");
        TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                .eq(TProjectAim::getProjectId, projectId)
                .eq(TProjectAim::getYear,LocalDate.now().getYear()));
        List<ProdPlanVO.PlanDetail> detailList = new ArrayList<>();
        ProdPlanVO.PlanDetail totalDetail = new ProdPlanVO.PlanDetail();
        ProdPlanVO.PlanDetail yearDetail = new ProdPlanVO.PlanDetail();
        ProdPlanVO.PlanDetail monthDetail = new ProdPlanVO.PlanDetail();
        ProdPlanVO.PlanDetail dayDetail = new ProdPlanVO.PlanDetail();
        totalDetail.setName("ZMB");
        yearDetail.setName("BNMB");
        monthDetail.setName("BYMB");
        dayDetail.setName("JRMB");
        if(Objects.isNull(projectAim)){
            totalDetail.setTotalNum(0);
            totalDetail.setFinishNum(0);
            totalDetail.setFinishRate(0D);
            yearDetail.setTotalNum(0);
            yearDetail.setFinishNum(0);
            yearDetail.setFinishRate(0D);
            monthDetail.setTotalNum(0);
            monthDetail.setFinishNum(0);
            monthDetail.setFinishRate(0D);
            dayDetail.setTotalNum(0);
            dayDetail.setFinishNum(0);
            dayDetail.setFinishRate(0D);
        }else {
            //查询项目已生产产品数量
            totalDetail.setTotalNum(total.getProdNum());
            totalDetail.setFinishNum(prodRecordService.sumRecord(projectId));
            Double totalFinishRate = new BigDecimal(totalDetail.getFinishNum()+"").divide(new BigDecimal(totalDetail.getTotalNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            totalDetail.setFinishRate(totalFinishRate * 100);
            //查询本年已生产数量
            yearDetail.setTotalNum(projectAim.getYearNum());
            yearDetail.setFinishNum(prodRecordService.sumYearRecord(projectId));
            Double yearFinishRate = new BigDecimal(yearDetail.getFinishNum()+"").divide(new BigDecimal(yearDetail.getTotalNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            yearDetail.setFinishRate(yearFinishRate * 100);
            //查询本月已生产数量
            monthDetail.setTotalNum(projectAim.getMonthNum());
            monthDetail.setFinishNum(prodRecordService.sumMonthRecord(projectId));
            Double monthFinishRate = new BigDecimal(monthDetail.getFinishNum()+"").divide(new BigDecimal(monthDetail.getTotalNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            monthDetail.setFinishRate(monthFinishRate * 100);
            //查询本日已生产数量
            dayDetail.setTotalNum(projectAim.getDayNum());
            dayDetail.setFinishNum(prodRecordService.sumDayRecord(projectId));
            Double dayFinishRate = new BigDecimal(dayDetail.getFinishNum()+"").divide(new BigDecimal(dayDetail.getTotalNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            dayDetail.setFinishRate(dayFinishRate * 100);
        }
        detailList.add(totalDetail);
        detailList.add(yearDetail);
        detailList.add(monthDetail);
        detailList.add(dayDetail);
        prodPlan.setDetailList(detailList);
        return prodPlan;
    }

    @Override
    public ProdPlanVO.PlanDetail taskFinishSchedule(Long projectId) {
        ProdPlanVO.PlanDetail taskDetail = new ProdPlanVO.PlanDetail();
        taskDetail.setName("scrw");
        //查询总生产任务数量
        taskDetail.setTotalNum(prodTaskService.sumPlanNum(projectId));
        //总生产数量
        taskDetail.setFinishNum(prodRecordService.sumRecord(projectId));
        if(taskDetail.getFinishNum() == 0){
            taskDetail.setFinishRate(0D);
        }else{
            Double finishRate = new BigDecimal(taskDetail.getFinishNum()+"").divide(new BigDecimal(taskDetail.getTotalNum()+""),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).doubleValue();
            taskDetail.setFinishRate(finishRate);
        }
        return taskDetail;
    }

    @Override
    public List<PieVO> prodFinishSchedule(Long projectId) {
        List<PieVO> pieList = prodRecordService.groupProd(projectId);
        int totalNum = prodRecordService.sumRecord(projectId);
        //处理产品名称
        pieList.forEach(item -> {
            TProd prod = prodService.getById(item.getName());
            SysDictData dictData = dictDataService.getByValue("sys_prod_unit",prod.getUnit());
            item.setName(prod.getSteel() + "-" + dictData.getDictLabel());
            Double rate = new BigDecimal(item.getVal()+"").divide(new BigDecimal(totalNum+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            item.setVal(rate * 100);
        });
        return pieList;
    }

    @Override
    public List<ProdYearTotalVO> prodYearTotal(Long projectId) {
        //获取年份统计
        List<ProdYearTotalVO> yearTotal = prodRecordService.groupYear(projectId);
        yearTotal.forEach(item -> {
            //获取生产目标
            TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                    .eq(TProjectAim::getProjectId, projectId)
                    .eq(TProjectAim::getYear,item.getYear()));
            //查询年实际产量
            Double rate = new BigDecimal(item.getFinishNum()+"").divide(new BigDecimal(projectAim.getYearNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
            item.setRate(rate * 100);
            List<PieVO> detail = new ArrayList<>();
            //每月产量统计
            List<PieVO> monthDetail = prodRecordService.groupMonth(projectId,item.getYear());
            for (int i = 1; i <= 12; i++) {
                PieVO pie = new PieVO();
                pie.setName(i+"");
                pie.setVal(0D);
                for(PieVO vo :monthDetail){
                    if(Integer.parseInt(vo.getName()) == i){
                        pie.setVal(vo.getVal());
                    }
                }
                detail.add(pie);
            }
            item.setDetail(detail);
        });
        return yearTotal;
    }

    @Override
    public ProdMonthTotalVO prodMonthTotal(Long projectId, String monthDate) {
        if(StringUtils.isBlank(monthDate)){
            //日期没传取当月
            monthDate = DateUtils.parseDateToStr("yyyy-MM",new Date());
        }
        ProdMonthTotalVO monthTotalVO = new ProdMonthTotalVO();
        monthTotalVO.setMonth(monthDate);
        List<PieVO> daysList = new ArrayList<>();
        //获取生产目标
        TProjectAim projectAim = projectAimService.getOne(new LambdaQueryWrapper<TProjectAim>()
                .eq(TProjectAim::getProjectId, projectId)
                .eq(TProjectAim::getYear,monthDate.substring(0,4)));
        //查询月实际产量
        int monthFinishNum = prodRecordService.sumXMonthRecord(projectId,monthDate);
        monthTotalVO.setFinishNum(monthFinishNum);
        Double rate = new BigDecimal(monthFinishNum+"").divide(new BigDecimal(projectAim.getMonthNum()+""),2,BigDecimal.ROUND_HALF_UP).doubleValue();
        monthTotalVO.setRate(rate * 100);
        //获取每天产量
        List<PieVO> daysDetail = prodRecordService.groupDay(projectId,monthDate);
        for (int i = 1; i <= LocalDate.now().lengthOfMonth(); i++) {
            PieVO pie = new PieVO();
            pie.setName(i+"");
            pie.setVal(0D);
            for(PieVO vo : daysDetail){
                if(Integer.parseInt(vo.getName()) == i){
                    pie.setVal(vo.getVal());
                }
            }
            daysList.add(pie);
        }
        monthTotalVO.setDetail(daysList);
        return monthTotalVO;
    }

}
